package com.itheima.email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 何杰
 * @date 11/1/2023 10:32 PM
 */

@Controller
public class EmailController {

    @Autowired
    private EmailService emailService;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private DynamicSchedulerService dynamicSchedulerService;
    String regex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
    Pattern pattern = Pattern.compile(regex);
    String fileName = "";
    String dirPath = "";
    String imgName = "";
    String imgPath = "";
    String timehour="";
    String timeminute="";
    String emailusername="";
    String emailtitle="";
    String emailtext="";
    String cron="";
    @ResponseBody
    @PostMapping("/emailText")
    public String emailText(@RequestParam("emailname") String emailname, @RequestParam("title") String title, @RequestParam("text") String text) {
        Matcher matcher = pattern.matcher(emailname);
        if (emailname.equals("")) {
            return "邮箱为空,请输入邮箱";
        } else {
            if (matcher.matches()) {
                if (text.equals("")) {
                    return "文本内容为空，请输入内容";
                } else {
                    if (text.length() <= 200) {
                        emailService.sendSimpleEmail(emailname, title, text);
                        return "纯文本邮件发送成功";
                    } else {
                        return "文本内容大于200字,请删除一些,当前字数:" + text.length() + "字";
                    }
                }
            } else {
                return "邮箱格式错误,请输入正确的邮箱地址";
            }
        }
    }

    @ResponseBody
    @PostMapping("/emailAnnex")
    public String emailAnnex(@RequestParam("file") MultipartFile[] fileUpload, @RequestParam("emailname") String emailname, @RequestParam("title") String title) {
        for (MultipartFile file : fileUpload) {
            //获取文件名以及后缀名
            fileName = file.getOriginalFilename();
            //重新生成文件名(根据具体情况生成对应文件名)
            //fileName = UUID.randomUUID() + "_" + fileName;
            //指定上传文件本地存储目录，不存在则需要提前创建
            dirPath = "D:\\hj\\file\\";
            File filePath = new File(dirPath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            try {
                file.transferTo(new File(dirPath + fileName));
            } catch (Exception e) {
                e.printStackTrace();
                //上传失败，返回失败信息
            }
        }
        Matcher matcher = pattern.matcher(emailname);
        if (emailname.equals("")) {
            return "邮箱为空,请输入邮箱";
        } else {
            if (matcher.matches()) {
                if (fileName.equals("")) {
                    return "请添加附件";
                } else {
                    emailService.sendComplexEmail(emailname, title, "", dirPath + fileName);
                    //F:\hj\file
                    //携带上传状态信息回调到文件上传页面
                    return "附件邮件发送成功";
                }
            } else {
                return "邮箱格式错误,请输入正确的邮箱地址";
            }
        }
    }

    @ResponseBody
    @PostMapping("/emailImg")
    public String emailImg(@RequestParam("img") MultipartFile[] fileUpload, @RequestParam("emailname") String emailname, @RequestParam("title") String title) {
        for (MultipartFile file : fileUpload) {
            //获取文件名以及后缀名
            imgName = file.getOriginalFilename();
            //重新生成文件名(根据具体情况生成对应文件名)
            //fileName = UUID.randomUUID() + "_" + fileName;
            //指定上传文件本地存储目录，不存在则需要提前创建
            imgPath = "D:\\hj\\img\\";
            File filePath = new File(imgPath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            try {
                file.transferTo(new File(imgPath + imgName));
            } catch (Exception e) {
                e.printStackTrace();
                //上传失败，返回失败信息
            }
        }
        Matcher matcher = pattern.matcher(emailname);
        String suffix = imgName.substring(imgName.lastIndexOf(".") + 1);
        if (emailname.equals("")){
            return "邮箱为空,请输入邮箱";
        }else {
            if (matcher.matches()){
                if (imgName.equals("")){
                    return "请添加图片";
                }else {
                    if (suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("png") || suffix.equalsIgnoreCase("bmp") || suffix.equalsIgnoreCase("jpeg"))  {
                        StringBuilder text = new StringBuilder();
                        text.append("<html><head></head>");
                        text.append("<body>");
                        String rscId = "img001";
                        text.append("<img src='cid:" +rscId+"'/></body>");text.append("</html>");
                        emailService.sendComplexEmail(emailname,title,text.toString(), rscId,imgPath+imgName);
                        //F:\hj\file
                        //携带上传状态信息回调到文件上传页面
                        return "图片邮件发送成功";
                    }else {
                        return "图片格式有误，请重新添加";
                    }
                }
            }else {
                return "邮箱格式错误,请输入正确的邮箱地址";
            }
        }
    }

    @ResponseBody
    @PostMapping("/emailTemplate")
    public String emailTemplate(@RequestParam("emailname") String emailname,@RequestParam("title") String title,@RequestParam("name") String name) {
        String randomNumber="";
        String randomNumber2="";
        Matcher matcher = pattern.matcher(emailname);
        if (emailname.equals("")){
            return "邮箱为空,请输入邮箱";
        }else {
            if (matcher.matches()){
                if (name.equals("")){
                    return "用户名为空,请输入用户名";
                }else {
                    Random random = new Random();
                    for (int i=0;i<6;i++){
                        randomNumber = String.valueOf(random.nextInt(10));
                        randomNumber2 += randomNumber;
                    }
                    Context context = new Context();
                    context.setVariable("username", name);
                    context.setVariable("code", randomNumber2);
                    String emailContent = templateEngine.process("email/emailverify", context);
                    emailService.sendTemplateEmail(emailname,title,emailContent);
                    return "模板邮件发送成功";
                }
            }else {
                return "邮箱格式错误,请输入正确的邮箱地址";
            }
        }
    }

    @ResponseBody
    @PostMapping("/emailAll")
    public String emailAll(@RequestParam("file") MultipartFile[] files ,@RequestParam("file1") MultipartFile[] files1,@RequestParam("emailname") String emailname, @RequestParam("title") String title,@RequestParam("text") String text1){
        for (MultipartFile file : files) {
            //获取文件名以及后缀名
            fileName = file.getOriginalFilename();
            dirPath = "D:\\hj\\file\\";
            File filePath = new File(dirPath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            try {
                file.transferTo(new File(dirPath + fileName));
            } catch (Exception e) {
                e.printStackTrace();
                //上传失败，返回失败信息
            }
        }
        for (MultipartFile file1 : files1) {
            imgName = file1.getOriginalFilename();
            imgPath = "D:\\hj\\img\\";
            File filePath = new File(dirPath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            try {
                file1.transferTo(new File(imgPath + imgName));
            } catch (Exception e) {
                e.printStackTrace();
                //上传失败，返回失败信息
            }
        }
        Matcher matcher = pattern.matcher(emailname);
        String suffix = imgName.substring(imgName.lastIndexOf(".") + 1);
        if (emailname.equals("")){
            return "邮箱为空,请输入邮箱";
        }else {
            if (matcher.matches()){
                if (text1.equals("")){
                    return "文本内容为空，请输入内容";
                }else {
                    if (text1.length()<=200){
                        if (fileName.equals("")){
                            return "请添加附件";
                        }else {
                            if (imgName.equals("")){
                                return "请添加图片";
                            }else {
                                if (suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("png") || suffix.equalsIgnoreCase("bmp") || suffix.equalsIgnoreCase("jpeg"))  {
                                    StringBuilder text = new StringBuilder();
                                    text.append("<html><head></head>");
                                    text.append("<body>");
                                    String rscId = "img001";
                                    text.append("<img src='cid:" +rscId+"'/></body>");text.append("</html>");
                                    emailService.sendComplexEmail(emailname,title,text.toString(),
                                            dirPath+fileName,rscId,imgPath+imgName);
                                    //携带上传状态信息回调到文件上传页面
                                    return "复杂邮件发送成功";
                                }else {
                                    return "图片格式有误，请重新添加";
                                }
                            }
                        }
                    }else {
                        return "文本内容大于200字,请删除一些,当前字数:" + text1.length() + "字";
                    }
                }
            }else {
                return "邮箱格式错误,请输入正确的邮箱地址";
            }
        }
    }

    @ResponseBody
    @PostMapping("/emailTiming")
    public String emailTiming(@RequestParam("emailname")String emailname,@RequestParam("title") String title,@RequestParam("text") String text,@RequestParam("week")String day,@RequestParam("time") String time){
        Matcher matcher = pattern.matcher(emailname);
        emailtitle=title;
        if (emailname.equals("")) {
            return "邮箱为空,请输入邮箱";
        }else {
            if (matcher.matches()) {
                emailusername=emailname;
                if (text.equals("")) {
                    return "文本内容为空，请输入内容";
                }else {
                    if (text.length() <= 200) {
                        emailtext=text;
                        if (day.equals("0")){
                            return "请选择你要设置的星期";
                        }else {
                            if (time.equals("")){
                                return "请选择你要设置的时间";
                            }else {
                                timehour = time.substring(0,time.lastIndexOf(":"));
                                timeminute = time.substring(time.lastIndexOf(":")+1);
                                cron = "0 "+timeminute+" "+timehour+" * * "+day;
                                dynamicSchedulerService.startScheduledTask(cron);
                                return "设置定时任务完成";
                            }
                        }
                    } else {
                        return "文本内容大于200字,请删除一些,当前字数:" + text.length() + "字";
                    }
                }
            }else {
                return "邮箱格式错误,请输入正确的邮箱地址";
            }
        }
    }
}
